package com.wenjie.reader;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.huashi.otg.sdk.HSIDCardInfo;
import com.huashi.otg.sdk.HandlerMsg;
import com.huashi.otg.sdk.HsOtgApi;

import java.text.SimpleDateFormat;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

/**
 * 身份证信息读取模块
 */
public class IdCardReaderModule extends UniModule {
    HsOtgApi api = null;
    boolean m_Con = false;
    private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式

    UniJSCallback callBack = null;

    @UniJSMethod(uiThread = true)
    public void sayHi(String name, UniJSCallback callback) {

        JSONObject callbackData = new JSONObject();

        callBack = callback;

        if (api == null) {
            api = new HsOtgApi(h, this.mWXSDKInstance.getContext());
        }
        int ret = api.init();
        if (ret == 1) {
            Log.i("读卡器初始化状态", "成功" + api.GetSAMID());
            m_Con = true;

        } else {
            if (ret == 2) {
                callbackData.put("status", "err");
                callbackData.put("msg", "设备未授权");
                callBack.invoke(callbackData);

            } else {
                callbackData.put("status", "err");
                callbackData.put("msg", "未找到设备");
                callBack.invoke(callbackData);
            }
            m_Con = false;
        }


        if (!m_Con) {
            callbackData.put("status", "err");
            callbackData.put("msg", "100U未连接");
            callBack.invoke(callbackData);
            return;
        }

        if (api.Authenticate(200, 10000) != 1) {
            callbackData.put("status", "err");
            callbackData.put("msg", "请重新放置身份证");
            callBack.invoke(callbackData);
            return;
        }
        Log.i("即将执行读卡", "执行读卡");
        HSIDCardInfo ici = new HSIDCardInfo();
        if (api.ReadCard(ici, 200, 15000) == 1) {
            Log.i("读卡成功", ici.toString());
            Message msg = Message.obtain();
            msg.obj = ici;
            msg.what = HandlerMsg.READ_SUCCESS;
            h.sendMessage(msg);
        } else {
            callbackData.put("status", "err");
            callbackData.put("msg", "读卡失败");
            callBack.invoke(callbackData);
        }
    }

    Handler h = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 99 || msg.what == 100) {
                JSONObject callbackData = new JSONObject();

                callbackData.put("status", "err");
                callbackData.put("msg", "未找到设备");
                callBack.invoke(callbackData);

                m_Con = false;
            }
            // 第一次授权时候的判断是利用handler判断，授权过后就不用这个判断了
            if (msg.what == HandlerMsg.CONNECT_SUCCESS) {
//                statu.setText("连接成功" + api.GetSAMID());

                m_Con = true;
                //sam.setText(api.GetSAMID());
            }
            if (msg.what == HandlerMsg.CONNECT_ERROR) {
//                statu.setText("连接失败");
            }
            if (msg.what == HandlerMsg.READ_ERROR) {
                // cz();
                // statu.setText("卡认证失败");
//                statu.setText("请放卡...");

            }
            if (msg.what == HandlerMsg.READ_SUCCESS) {

                HSIDCardInfo ic = (HSIDCardInfo) msg.obj;
                byte[] fp = new byte[1024];
                fp = ic.getFpDate();
                String m_FristPFInfo = "";
                String m_SecondPFInfo = "";

//                if (fp[4] == (byte) 0x01) {
//                    m_FristPFInfo = String.format(
//                            "指纹  信息：第一枚指纹注册成功。指位：%s。指纹质量：%d \n",
//                            GetFPcode(fp[5]), fp[6]);
//                } else {
//                    m_FristPFInfo = "身份证无指纹 \n";
//                }
//                if (fp[512 + 4] == (byte) 0x01) {
//                    m_SecondPFInfo = String.format(
//                            "指纹  信息：第二枚指纹注册成功。指位：%s。指纹质量：%d \n",
//                            GetFPcode(fp[512 + 5]), fp[512 + 6]);
//                } else {
//                    m_SecondPFInfo = "身份证无指纹 \n";
//                }
                if (ic.getcertType() == " ") {
                    Log.i("读取身份证信息返回", "证件类型：身份证\n" + "姓名：" + ic.getPeopleName()
                            + "\n" + "性别：" + ic.getSex() + "\n" + "民族："
                            + ic.getPeople() + "\n" + "出生日期："
                            + df.format(ic.getBirthDay()) + "\n" + "地址："
                            + ic.getAddr() + "\n" + "身份号码：" + ic.getIDCard()
                            + "\n" + "签发机关：" + ic.getDepartment() + "\n"
                            + "有效期限：" + ic.getStrartDate() + "-"
                            + ic.getEndDate() + "\n" + m_FristPFInfo + "\n"
                            + m_SecondPFInfo);
                    if (callBack != null) {
                        JSONObject invokeJson = new JSONObject();
                        invokeJson.put("peopleName", ic.getPeopleName());
                        invokeJson.put("sex", ic.getSex());
                        invokeJson.put("people", ic.getPeople());
                        invokeJson.put("birthDay", df.format(ic.getBirthDay()));
                        invokeJson.put("addr", ic.getAddr());
                        invokeJson.put("iDCard", ic.getIDCard());
                        callBack.invoke(invokeJson);
                    }
//                        callBack.invoke("证件类型：身份证\n" + "姓名：" + ic.getPeopleName()
//                            + "\n" + "性别：" + ic.getSex() + "\n" + "民族："
//                            + ic.getPeople() + "\n" + "出生日期："
//                            + df.format(ic.getBirthDay()) + "\n" + "地址："
//                            + ic.getAddr() + "\n" + "身份号码：" + ic.getIDCard()
//                            + "\n" + "签发机关：" + ic.getDepartment() + "\n"
//                            + "有效期限：" + ic.getStrartDate() + "-"
//                            + ic.getEndDate() + "\n" + m_FristPFInfo + "\n"
//                            + m_SecondPFInfo);
                } else {
                    if (ic.getcertType() == "J") {
                        if (callBack != null)
                            callBack.invoke("证件类型：港澳台居住证（J）\n" + "姓名："
                                    + ic.getPeopleName() + "\n" + "性别："
                                    + ic.getSex() + "\n" + "签发次数："
                                    + ic.getissuesNum() + "\n" + "通行证号码："
                                    + ic.getPassCheckID() + "\n" + "出生日期："
                                    + df.format(ic.getBirthDay()) + "\n" + "地址："
                                    + ic.getAddr() + "\n" + "身份号码："
                                    + ic.getIDCard() + "\n" + "签发机关："
                                    + ic.getDepartment() + "\n" + "有效期限："
                                    + ic.getStrartDate() + "-" + ic.getEndDate()
                                    + "\n" + m_FristPFInfo + "\n" + m_SecondPFInfo);
                    } else {
//                        if (ic.getcertType() == "I") {
//                            tv_info.setText("证件类型：外国人永久居留证（I）\n" + "英文名称："
//                                    + ic.getPeopleName() + "\n" + "中文名称："
//                                    + ic.getstrChineseName() + "\n" + "性别："
//                                    + ic.getSex() + "\n" + "永久居留证号："
//                                    + ic.getIDCard() + "\n" + "国籍："
//                                    + ic.getstrNationCode() + "\n" + "出生日期："
//                                    + df.format(ic.getBirthDay()) + "\n"
//                                    + "证件版本号：" + ic.getstrCertVer() + "\n"
//                                    + "申请受理机关：" + ic.getDepartment() + "\n"
//                                    + "有效期限：" + ic.getStrartDate() + "-"
//                                    + ic.getEndDate() + "\n" + m_FristPFInfo
//                                    + "\n" + m_SecondPFInfo);
//                        }
                    }

                }


            }
        }
    };
}
